/*
 * ActionDeployer.java July 2009
 *
 * Copyright (C) 2009, Quirino Zagarese <quirino@laszloitalia.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */
package org.eu4ria.core;

import java.lang.reflect.Method;

import javassist.bytecode.annotation.Annotation;

import org.eu4ria.AppAction;
import org.eu4ria.exceptions.UnsupportedParameterTypeException;

public class ActionDeployer {

	private static ActionDeployer instance;

	private ParameterDeployer parameterDeployer = ParameterDeployer.getInstance();

	private ActionDeployer(){

	}


	public static ActionDeployer getInstance(){
		if(instance == null){
			instance = new ActionDeployer();
		}
		return instance;
	}


	public AppAction deployAction(Method m) throws Exception {
		AppAction action = new AppAction();
		action.setJavaMethod(m);
		Annotation[][] paramsAnnotations = AnnotationScanner.getParametersAnnotations(m);
		Class[] types = m.getParameterTypes();
		for(int i = 0; i < paramsAnnotations.length ; i++){
			Annotation[] annotations = paramsAnnotations[i];
			int j = 0;
			for(j = 0; j < annotations.length; j++){
				if(parameterDeployer.isAnnotationSupported(annotations[j])){
					action.addParameter(parameterDeployer.deployParameter(types[i],annotations[j]));
					break;
				}
			}
			if((annotations.length == 0)||(j == annotations.length)){
				if(parameterDeployer.isTypeSupported(types[i].getName())){
					action.addParameter(parameterDeployer.deployParameter(types[i], null));
				}else{
					throw new UnsupportedParameterTypeException("Type " + types[i].getName() + " is not currently supported.");
				}
			}
		}
		return action;
	}

}
